package com.github.data_manage.controller

import com.github.data_manage.common.CommonPage
import com.github.data_manage.common.CommonResult
import com.github.data_manage.common.CompaniesEnum
import com.github.data_manage.common.ResultCode
import com.github.data_manage.dao.RoleDao
import com.github.data_manage.dao.UserDao
import com.github.data_manage.domain.po.Role
import com.github.data_manage.domain.vo.RolePageParam
import com.github.data_manage.util.PageUtil
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.transaction.Transactional
import org.springframework.data.domain.Sort
import org.springframework.data.jpa.domain.Specification
import org.springframework.util.StringUtils
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

/**
 *@author CHN
 *@since 2024-08-18 16:41
 */
@RestController
@RequestMapping("/role")
@Tag(name = "RoleController", description = "角色管理")
class RoleController(
    private val roleDao: RoleDao,
    private val userDao: UserDao
) {

    @PostMapping("/saveOrUpdate")
    @Operation(description = "新增/编辑角色")
    @Transactional(rollbackOn = [Exception::class])
    fun saveOrUpdate(@RequestBody role: Role): CommonResult<String>{
        roleDao.save(role)
        return CommonResult.success(ResultCode.SUCCESS.message)
    }

    @Operation(description = "删除角色")
    @DeleteMapping(value = ["/delete"])
    @Transactional(rollbackOn = [Exception::class])
    fun deleteCompanyById(@RequestBody roleIds: Collection<Int>): CommonResult<String> {
        roleDao.findAllById(roleIds).forEach { role ->
            userDao.removeAllByRole(role)
        }
        roleDao.deleteAllById(roleIds)
        return CommonResult.success(CompaniesEnum.DELETE_SUCCESS.message);
    }

    @Operation(description = "角色列表")
    @RequestMapping(value = ["/list"], method = [RequestMethod.POST])
    @ResponseBody
    fun getCompanyList(@Validated @RequestBody rolePageParam: RolePageParam): CommonResult<CommonPage<Role>> {
        val condition = Specification<Role> { root, _, builder ->
            if (StringUtils.hasText(rolePageParam.roleName)) {
                return@Specification builder.like(
                    root.get<String>("name"),
                    "%${rolePageParam.roleName}%"
                )
            }
            return@Specification builder.isNotNull(root.get<Int>("id"))
        }
        val page = PageUtil.buildJpaPage<Role>(rolePageParam.pageNum, rolePageParam.pageSize)

        return CommonResult.success(
            CommonPage.restPage(roleDao.findAll(condition, page)))
    }

}